const express = require('express')
const router = express()
var AV = require('leanengine');
var AgnScore = AV.Object.extend('AgnScore');

router.get('/', (req, res) => {
    var query = new AV.Query(AgnScore);
    if(req.query.acid){
        query.equalTo('acid',req.query.acid);
    }
    if(req.query.author){
        query.equalTo('author',req.query.author);
    }
    if(req.query.comment){
        query.equalTo('comment',req.query.comment);
    }
    if(req.query.orderBy){
        if(req.query.reverse){
            query.addDescending(req.query.orderBy)
        }else {
            query.addAscending(req.query.orderBy)
        }
    }else {
        query.addDescending('createdAt');
    }
    let pagesize = req.query.pageSize||20;
    let page = req.query.page||1;
    query.skip((page-1)*pagesize)
    query.limit(pagesize)
    query.find().then(results => {
        res.send({code:200,data:results})
    },error =>{
        res.send({code:500,message:error.message})
    })
})

router.post('/:acid', (req, res) => {
    var query = new AV.Query(AgnScore);
    query.equalTo('acid',req.body.acid);
    query.equalTo('comment',req.body.comment.trim());
    query.find().then( results =>{
        if(results.length>0){
            res.send({message:'ok',code:200})
        }else {
            var content = new AgnScore();
            for(let key in req.body){
                content.set(key, req.body[key]);
            }
            content.save().then(content => {
                // 成功保存之后，执行其他逻辑.
                res.send({message:'ok',code:200})
            }, error => {
                // 异常处理
                console.error('Failed to create new object, with error message: ' + error.message);
                res.send({message:error.message,code:500})
            });
        }
    },error =>{
        res.send({code:500,message:error.message})
    })
})

module.exports = router